package com.example.capsule_chat0322.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.activity.UpdateInfoActivity;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.connect.PositionOperation;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.layout.ItemGroup;
import com.example.capsule_chat0322.request.UserInfoRequest;

import java.util.Random;

/**
 * @Author zhuzhiming
 * @Date 2022/5/1 16:54
 */
public class PersonFragment extends Fragment implements View.OnClickListener {

    private TextView user_info_update;
    private AppCompatImageView user_avatar;
    private UserInfoBean userInfoBean;
    private boolean isFirst = true;
    private int imgId = 0;
    private ItemGroup user_id;
    private ItemGroup user_nickname;
    private ItemGroup user_sign;
    private ItemGroup user_sex;
    private ItemGroup user_age;
    private ItemGroup user_hobby;
    private ItemGroup user_email;
    private static View view;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getParentFragmentManager().setFragmentResultListener("skipToChatRoomListMark", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
                String result = bundle.getString("isSkip");
                if (result != null && GlobalAssistMap.getObject("avatar") != null) {
                    isFirst = false;
                }
            }
        });

        Bundle result = new Bundle();
        result.putString("isSkip", "true");
        getParentFragmentManager().setFragmentResult("skipToChatRoomListMark", result);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.person, container, false);
        PersonFragment.view = view;
        Bundle result = new Bundle();
        result.putString("isSkip", "true");
        getParentFragmentManager().setFragmentResult("skipToChatRoomListMark", result);
        initView(view);
        return view;

    }

    public void initView(View view) {


        user_id = view.findViewById(R.id.user_id);
        user_nickname = view.findViewById(R.id.user_nickname);
        user_sign = view.findViewById(R.id.user_sign);
        user_sex = view.findViewById(R.id.user_sex);
        user_age = view.findViewById(R.id.user_age);
        user_hobby = view.findViewById(R.id.user_hobby);
        user_email = view.findViewById(R.id.user_email);

        user_info_update = view.findViewById(R.id.user_info_update);
        user_avatar = view.findViewById(R.id.user_avatar);



        if (GlobalAssistMap.getObject("userInfo") != null) {

            userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
            user_id.getContentEdt().setText(GlobalAssistMap.getObject("userId").toString());
            user_nickname.getContentEdt().setText(userInfoBean.getNickname());
            user_sign.getContentEdt().setText(userInfoBean.getSign());
            user_sex.getContentEdt().setText(userInfoBean.getSex() == -1 ? "" : userInfoBean.getSex() == 1 ? "男" : "女");
            user_age.getContentEdt().setText(userInfoBean.getAge() == -1 ? "" : String.valueOf(userInfoBean.getAge()));
            user_hobby.getContentEdt().setText(userInfoBean.getHobby());
            user_email.getContentEdt().setText(userInfoBean.getEmail());
            String avatarStr = userInfoBean.getAvatarUrl();
            if (avatarStr.contains("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarStr);
                if (bitmap != null) {
                    user_avatar.setImageBitmap(bitmap);
                } else {
                    Random random = new Random();
                    Class cls2 = R.drawable.class;
                    try {
                        imgId = cls2.getField("img_" + random.nextInt(2) + random.nextInt(10)).getInt(null);
                        user_avatar.setImageResource(imgId);
                    } catch (IllegalAccessException | NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                    //AlterUtils.alertByToastInSonThread(getActivity(), "本地头像找不到了~");
                }

            } else {
                user_avatar.setImageResource(Integer.parseInt(avatarStr));
            }

        }


        Handler handler = new Handler(new Handler.Callback() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public boolean handleMessage(@NonNull Message message) {
                userInfoBean = (UserInfoBean) message.obj;
                if (userInfoBean == null) {
                    return true;
                }

                user_id.getContentEdt().setText(GlobalAssistMap.getObject("userId").toString());
                user_nickname.getContentEdt().setText(userInfoBean.getNickname());
                user_sign.getContentEdt().setText(userInfoBean.getSign());
                user_sex.getContentEdt().setText(userInfoBean.getSex() == -1 ? "" : userInfoBean.getSex() == 1 ? "男" : "女");
                user_age.getContentEdt().setText(userInfoBean.getAge() == -1 ? "" : String.valueOf(userInfoBean.getAge()));
                user_hobby.getContentEdt().setText(userInfoBean.getHobby());
                user_email.getContentEdt().setText(userInfoBean.getEmail());

                if (userInfoBean.getAvatarUrl() == null || userInfoBean.getAvatarUrl().equals("") || userInfoBean.getAvatarUrl().equals("0")) {

                    Random random = new Random();
                    Class cls2 = R.drawable.class;

                    try {
                        imgId = cls2.getField("img_" + random.nextInt(2) + random.nextInt(10)).getInt(null);
                        user_avatar.setImageResource(imgId);
                    } catch (IllegalAccessException | NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                } else {

                    if (userInfoBean.getAvatarUrl().contains("/")) {
                        String avatarStr = userInfoBean.getAvatarUrl();
                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                        Bitmap bitmap = (Bitmap) lruCache.get(avatarStr.substring(avatarStr.lastIndexOf("/")));
                        if (bitmap == null) {
                            bitmap = BitmapFactory.decodeFile(avatarStr);
                            if (bitmap == null) {
                                UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                                    @Override
                                    public boolean handleMessage(@NonNull Message message) {
                                        String path = Constant.IMAGE_PATH + userInfoBean.getAvatarUrl().substring(userInfoBean.getAvatarUrl().lastIndexOf("/") + 1);
                                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                                        lruCache.put(avatarStr.substring(avatarStr.lastIndexOf("/") + 1), bitmap);
                                        GlobalAssistMap.putObject("avatar", userInfoBean.getAvatarUrl());
                                        user_avatar.setImageBitmap(bitmap);
                                        return true;
                                    }
                                }), userInfoBean.getAvatarServerPath());
                            } else {
                                lruCache.put(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                                user_avatar.setImageBitmap(bitmap);
                                GlobalAssistMap.putObject("avatar", userInfoBean.getAvatarUrl());
                            }

                            // GlobalAssistMap.putObject(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                        } else {
                            user_avatar.setImageBitmap(bitmap);
                            GlobalAssistMap.putObject("avatar", userInfoBean.getAvatarUrl());
                        }
                    } else {
                        imgId = Integer.parseInt(userInfoBean.getAvatarUrl());
                        user_avatar.setImageResource(imgId);
                        GlobalAssistMap.putObject("avatar", String.valueOf(imgId));
                    }
                }

                GlobalAssistMap.putObject("userInfo", userInfoBean);

                PositionOperation.getLocation(getContext(), null);

                return true;
            }
        });

        if (isFirst) {
            String userId = (String) GlobalAssistMap.getObject("userId");
            if (userId == null) {
                try {
                    Thread.sleep(100);
                    userId = (String) GlobalAssistMap.getObject("userId");
                    if (userId == null) {
                        Thread.sleep(300);
                        userId = (String) GlobalAssistMap.getObject("userId");
                        if (userId == null) {
                            Thread.sleep(500);
                            userId = (String) GlobalAssistMap.getObject("userId");
                        }

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (userId == null) {
                return;
            }
            UserInfoRequest.doGetUserInfoRequest(handler, userId);
            isFirst = false;
        }

        user_info_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setClass(getActivity(), UpdateInfoActivity.class);
                startActivity(intent);
                Handler handler = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(@NonNull Message message) {

                        String isNeedUpdate = (String) message.obj;
                        if (isNeedUpdate.equals(Constant.SUCCESS)) {
                            initView(PersonFragment.view);
                        }
                        return true;

                    }
                });

                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        while (GlobalAssistMap.getObject("update") == null) {

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        String isNeedUpdate = GlobalAssistMap.getObject("update").toString();

                        if (isNeedUpdate.equals(Constant.SUCCESS)) {
                            handler.sendMessage(handler.obtainMessage(1, Constant.SUCCESS));
                        } else {
                            handler.sendMessage(handler.obtainMessage(1, Constant.FAIL));
                        }

                        GlobalAssistMap.removeObject("update");

                    }
                });
            }
        });
    }

    @Override
    public void onClick(View view) {

    }


}
